import React, { useState } from 'react';
import { Form, Icon, Input, Button, message } from 'antd';
import axios from 'axios';

import LoginStyles from './login.module.css';


const Login = () => {

    const [loginForm, setLoginForm] = useState({username: '', password: ''});
    const [submitPending, setSubmitPending] = useState(false);


    const submitForm = async () => {
        const { username, password } = loginForm;
        if (!username) {
            message.error('用户名不能为空');
            return;
        }
        if (!password) {
            message.error('密码不能为空');
            return;
        }

        if (submitPending) return;
        setSubmitPending(true);

        try {
            const loginRes = (await axios({
                method: 'post',
                url: '/api/login',
                data: loginForm,
            })).data;

            if (loginRes.code !== 0) {
                message.error(loginRes.err);
            } else {
                message.success('登录成功');
                window.location.href = 'http://zhuyp.ccimm.top/admin'
            }
        } catch (e) {
            message.error('服务器错误');
            console.log(e);
        } finally {
            setSubmitPending(false);
        }
    };

    return <div className={LoginStyles.loginWrapper}>
        <div className={LoginStyles.loginMask}>
            <div className={LoginStyles.formWrapper}>
                <Form onSubmit={submitForm}>
                    <Form.Item label="用户名">
                        <Input value={loginForm.username}
                               onChange={(event) => {
                                   const username = event.target.value;
                                   setLoginForm(prevState => ({...prevState, username}))
                               }}
                               prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                               placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item label="密码">
                        <Input
                            value={loginForm.password}
                            onPressEnter={submitForm}
                            onChange={event => {
                                const password = event.target.value;
                                setLoginForm(prevState => ({
                                    ...prevState, password
                                }))
                            }}
                            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            type="password"
                            placeholder="请输入密码"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={submitForm}>登录</Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    </div>
};


export default Login;
